﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;
using ZK.InterfaceServer;

namespace ZK.InterfaceServer
{
    public class TestConnect
    {
        private static object obj = new object();
        private static int PingTime = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("PingTime"));
        /// <summary>
        /// test tcpip
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public static bool TestConnectIp(string ip, int port)
        {
            lock (obj)
            {
                bool res = false;
                int seconds = Convert.ToInt32(AppConfigHelper.GetAppSettings("WebSocketTime"));
                System.Diagnostics.Stopwatch swThd = System.Diagnostics.Stopwatch.StartNew();
                IPAddress iPAddress = IPAddress.Parse(ip);
                IPEndPoint point = new IPEndPoint(iPAddress, port);
                using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            sock.Connect(point);
                            res = true;
                        }
                        catch (Exception e)
                        {
                            Common.Log4.LogManage.WriteErr("TestConnectIp " + ip + ":" + e.Message);
                        }
                    }).Wait(seconds * 1000);
                    sock.Close();
                    if (!res) Common.Log4.LogManage.WriteErr(ip + ":连接超时、ip端口不正确");
                    return res;
                }
            }
        }

        /// <summary>
        /// Ping固定IP 如果不通，写数据异常
        /// </summary>
        /// <param name="str_ip">IP地址</param>
        /// <returns>成功返回1，失败返回0</returns>
        public static void CheckDeviceStatus(string str_ip, string name)
        {
            lock (obj)
            {
                PingReply reply = null;
                Task.Factory.StartNew(() =>
                {
                    Ping pinSender = new Ping();
                    PingOptions options = new PingOptions();
                    string data = "";
                    byte[] buffer = Encoding.ASCII.GetBytes(data);
                    options.DontFragment = true;
                    int timeout = Convert.ToInt32(AppConfigHelper.GetAppSettings("PingIpTime"));
                    reply = pinSender.Send(str_ip, timeout, buffer, options);
                }).Wait(PingTime);

                if (reply == null || (reply.Status != IPStatus.Success))
                {
                    string msg = "ip:" + str_ip + " 名称：" + name + " 信息：网络异常，ping失败";
                    AutoControlTransportApiServer.AddHardWareLog(name, 1, msg);
                    Common.Log4.LogManage.WriteErr(msg);
                    Common.DelegateHelper.InfoMessageEvent?.Invoke(msg);
                }
            }
        }
    }
}
